import re

from flask import Blueprint,request,make_response,jsonify,redirect
from flask_restful import reqparse
from util.myjwt import myjwt
from util.captcha.captcha import captcha
import json, random, time, requests
from util.myredis import r
from util.smssdk import send_message
from models.user import *

user_blue = Blueprint("userblue",__name__)


@user_blue.route("/getImageCode")
def getImageCode():
    # 生成图片验证码 text文字   image图片流
    name, text, image = captcha.generate_captcha()
    # 从页面获取uuid做为redis key
    uuid = request.args.get("uuid")
    # 存入redis
    r.str_setex(uuid, text, 300)
    # 以流的方式生成图片验证码
    res = make_response(image)
    res.headers["Content-Type"] = 'image/jpg'
    return res

@user_blue.route('/sendsms',methods=['POST'])
def sms():
    data = request.data
    if data:
        data = json.loads(data)
        mobile = data['mobile']
        uuid = data['uuid']
        imagecode = data['imagecode']
        # 获取图片验证码
        code = r.str_get(uuid)
        if code:
            if imagecode.lower() != code.decode().lower():
                return jsonify({'code':10200,'msg':'验证码有误'})
            # 获取之后删除图片验证码
            r.del_key(uuid)
        else:
            return jsonify({'code':10201,'msg':'图片验证码不存在'})
        if not re.findall(r'^1[3-9]\d{9}$',mobile):
            return jsonify({'code':10023,'msg':'手机号格式有误'})
        v = r.str_get(mobile)
        if v:
            return jsonify({'code':10202,'msg':'一分钟只能发送一次'})
        c = send_message(mobile)
        print(c)
        return jsonify({'code':200,'msg':'发送成功'})
@user_blue.route('/login',methods=['POST'])
def login():
    data = request.data

    if data:
        data = json.loads(data)
        mobile = data['mobile']
        sms = data['sms']
        smscode = r.str_get(mobile)
        if smscode:
            if smscode.decode() != sms:
                return jsonify({'code':10022,'msg':'验证码有误'})
            user = User.query.filter_by(mobile=mobile).first()
            if user:
                token = myjwt.jwt_encode({'data':{'userid':user.id,'mobile':user.mobile},'exp':int(time.time())})
                return jsonify({'code':200,'msg':'登录成功','token':token,'userid':user.id})
            else:
                create_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                user = User(mobile=mobile,create_time=create_time)
                db.session.add(user)
                db.session.commit()
                return jsonify({'code':201,'msg':'注册成功'})

        else:
            return jsonify({'code':10200,'msg':'验证码过期'})
    else:
        return jsonify({'code': 10200, 'msg': '请输入账号'})

@user_blue.route('/wblogin')
def wblogin():
    client_id = '3674019597'
    redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
    url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
        client_id, redirect_uri)
    return jsonify({'code':200,'url':url})
@user_blue.route('/user/weiboCallback/')
def wbcallback():
    req = reqparse.RequestParser()
    req.add_argument('code')
    args =req.parse_args()
    code = args['code']
    data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
            "grant_type": "authorization_code",
            'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
    res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
    # 根据返回结果操作
    # 获取token和uid
    message = json.loads(res.text)
    token = message['access_token']
    uid = message['uid']
    sflogin = db.session.execute("select * from user u inner join sflogin s on u.id = s.userid where s.uid=%s"%(uid))
    sf = list(sflogin)
    # 获取的数据是个转换成list，里面的数据是值，根据索引获取
    if sf:
        for i in sf:
            token = myjwt.jwt_encode(data={'data':{'uid':i[0],'exp':int(time.time())}})
            return redirect("http://localhost:8080/updatetoken?token=" + token + "&userid=" + str(i[0]))
    else:
        return redirect("http://localhost:8080/bingmobile?token=" + str(token) + "&uid=" + str(uid))

@user_blue.route('/bingmobile',methods=['POST'])
def bingmobile():
    data = json.loads(request.data)
    mobile = data['mobile']
    try:
        user = User(mobile=mobile)
        db.session.add(user)
        db.session.commit()
        uid = data['uid']
        token = data['token']
        # users= User.query.filter_by(mobile=mobile).first()
        # print(users)
        sf = sf_login(uid=uid,token=token,webfrom='微博',userid=int(user.id))
        db.session.add(sf)
        db.session.commit()
    except:
        return jsonify({'code':10020,'msg':'擦'})

    token = myjwt.jwt_encode(data={'data':{'uid':user.id,'exp':int(time.time())}})
    return jsonify({'code':200,'token':token,'userid':user.id})

# def aaa():
#     roles = db.session.execute("select * from user")
#     cc = list(roles)
#     print(cc)
#     for i in cc:
#         print(i[0])
# aaa()

